<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-22
 * Time: 22:20
 */

namespace plugin\csauto\app\process;


use plugin\csauto\app\model\DownloaderModel;
use plugin\csauto\app\model\SiteModel;
use plugin\csauto\app\model\TorrentTaskModel;
use plugin\csauto\app\service\downloader\DownloaderWorkService;
use plugin\csauto\app\service\RssWorkService;
use support\Log;
use Workerman\Crontab\Crontab;
use Workerman\Timer;

/**
 * Class DownloaderCheckTaskProcess
 * 步骤4
 * 检查下载器的源任务是否已经完成
 *
 * @package plugin\csauto\app\process
 */
class DownloaderCheckTaskProcess
{
    // 定时器句柄/ID
    protected $timer;
    protected $wechatTimer;
    protected $torrentTaskMaxNum = 2;

    // 时间间隔 (单位: 秒, 默认5秒)
    protected $interval = 60;

    public function onWorkerStart()
    {
        if (getenv('WORK_DEBUG')) return true;
        $this->timer = Timer::add($this->interval, function () {
            try {
                // 这里执行系统预设的定时任务事件
                $this->run();
            } catch (\Throwable $e) {
                echo 'ERROR[DownloaderCheckTaskProcess]: ' . $e->getMessage() . PHP_EOL;
            }
        });

        return true;
    }

    public function run()
    {
        addlog('下载器-检查任务', 'start');
        $siteList = array();
        foreach (SiteModel::get() as $item) {
            $siteList[$item->id] = $item;
        }
        /*检查未完成的任务情况*/
        $downloaderList = DownloaderModel::where('status', 1)->get();
        foreach ($downloaderList as $item) {
            /*检查源站种状态*/
            addlog('DownloaderCheckTaskProcess', "源种站DownloaderId：{$item->id},checkDownloadTask检查");
            DownloaderWorkService::checkDownloadTask($item);
            /*检查发布种子状态*/
            addlog('DownloaderCheckTaskProcess', "源种站DownloaderId：{$item->id},updateDownloaderStatus检查");
            DownloaderWorkService::updateDownloaderStatus($item,$siteList);
        }
        return '任务调用：' . date('Y-m-d H:i:s') . "\n";
    }

    /**
     * 停止/删除定时器
     *
     * @return bool
     */
    public function stop()
    {
        return Timer::del($this->timer);
    }

}